#include <QColorDialog>
#include <QStylePainter>
#include <QStyleOptionButton>
#include <QStyleOptionToolButton>
#include <QPushButton>
#include "colorbutton.h"

namespace ShUi
{

class ColorButtonImpl : public Impl<ColorButton>
{
public:
    void init();
    void exit();
    QColor _color;
};

void ColorButtonImpl::init()
{
    SH_Q(ColorButton);
    q->connect(q, SIGNAL(clicked()), q, SLOT(onClicked()));
}

void ColorButtonImpl::exit()
{
}

ColorButton::ColorButton(QWidget* parent) :
    QToolButton(parent)
{
    SH_I(ColorButton);
    d->init();
    setColor(0, 0, 0);
}

ColorButton::ColorButton(const QColor& color, QWidget* parent) :
    QToolButton(parent)
{
    SH_I(ColorButton);
    d->init();
    setColor(color);
}

ColorButton::~ColorButton()
{
    SH_E(ColorButton);
    d->exit();
}

QColor ColorButton::color() const
{
    SH_D(const ColorButton);
    return d->_color;
}

void ColorButton::setColor(const QColor& color)
{
    SH_D(ColorButton);
    if (d->_color != color)
    {
    	d->_color = color;
     	repaint();
        emit colorChanged(color);
    }
}

void ColorButton::setColor(int r, int g, int b)
{
    setColor(QColor(r, g, b));
}

void ColorButton::onClicked()
{
    QColor col = QColorDialog::getColor(color(), this);
    if (col.isValid())
        setColor(col);
}

void ColorButton::paintEvent(QPaintEvent* evt)
{
    SH_D(ColorButton);
    QToolButton::paintEvent(evt);
    QStylePainter p(this);
    QStyleOptionToolButton opt;
    initStyleOption(&opt);
    bool selected = opt.state & QStyle::State_MouseOver;
    bool pressed = opt.state & QStyle::State_Sunken;
    bool enabled = opt.state & QStyle::State_Enabled;
    QStyle::State state = QStyle::State_None;
    if (enabled)
	state |= QStyle::State_Enabled;
    QPushButton* btn = new QPushButton();
    btn->setEnabled(enabled);
    if ((enabled && !selected && !pressed) || !enabled)
    {
        QStyleOptionButton btnOpt;
        btnOpt.initFrom(btn);
        btnOpt.rect = opt.rect;
        btnOpt.state = state;
        btnOpt.icon = QIcon();
        style()->drawControl(QStyle::CE_PushButton, &btnOpt, &p, SH_NULL);
    }
    delete btn;

    QRect rect(opt.rect);
    rect.adjust(2, 3, -2, -3);
    QColor color = isEnabled() ? d->_color : QColor(200, 200, 200);
    p.fillRect(rect, color);
}

} // namespace ShUi
